import React, { useState } from 'react';

import { DownOutlined, UpOutlined } from '@ant-design/icons';

import type { CardProps } from 'antd';

// 从 CardProps 中排除 children 属性，因为我们会在 ExpandableCardProps 中重新定义
export interface ExpandableCardProps extends Omit<CardProps, 'extra' | 'children'> {
  /** 卡片标题 */
  title?: React.ReactNode;
  /** 是否默认展开 */
  defaultExpanded?: boolean;
  /** 展开状态改变回调 */
  onExpandChange?: (expanded: boolean) => void;
  /** 自定义展开按钮 */
  expandButton?: (expanded: boolean, toggle: () => void) => React.ReactNode;
  /** 展开按钮的提示文字 */
  expandTooltip?: {
    expand: string;
    collapse: string;
  };
  /** 是否显示展开按钮 */
  showExpandButton?: boolean;
  /** 额外的操作按钮（会显示在展开按钮左侧） */
  extraActions?: React.ReactNode;
  /** 子元素渲染函数，接收展开状态 */
  children?: React.ReactNode | ((expanded: boolean) => React.ReactNode);
}

export interface ExpandableContentProps {
  /** 是否展开 */
  expanded: boolean;
  /** 基础内容（始终显示） */
  basicContent: React.ReactNode;
  /** 扩展内容（展开时显示） */
  expandedContent: React.ReactNode;
  /** 动画持续时间 */
  animationDuration?: number;
}

const ExpandableCard: React.FC<ExpandableCardProps> = ({
  title,
  defaultExpanded = false,
  onExpandChange,
  expandButton,
  expandTooltip = { expand: '展开', collapse: '收缩' },
  showExpandButton = true,
  extraActions,
  children,
  className,
  ...cardProps
}) => {
  const [isExpanded, setIsExpanded] = useState(defaultExpanded);

  const handleToggle = () => {
    const newExpanded = !isExpanded;
    setIsExpanded(newExpanded);
    onExpandChange?.(newExpanded);
  };

  // 渲染展开按钮
  const renderExpandButton = () => {
    if (!showExpandButton) return null;

    if (expandButton) {
      return expandButton(isExpanded, handleToggle);
    }

    return (
      <AButton
        type="text"
        icon={isExpanded ? <UpOutlined /> : <DownOutlined />}
        onClick={handleToggle}
        title={isExpanded ? expandTooltip.collapse : expandTooltip.expand}
        size="small"
      />
    );
  };

  // 渲染额外操作区域
  const renderExtra = () => {
    const expandBtn = renderExpandButton();

    if (!extraActions && !expandBtn) {
      return undefined;
    }

    if (!extraActions) {
      return expandBtn;
    }

    if (!expandBtn) {
      return extraActions;
    }

    return (
      <ASpace size="small">
        {extraActions}
        {expandBtn}
      </ASpace>
    );
  };

  // 渲染子内容
  const renderChildren = () => {
    if (typeof children === 'function') {
      return children(isExpanded);
    }
    return children;
  };

  return (
    <ACard title={title} extra={renderExtra()} className={className} {...cardProps}>
      {renderChildren()}
    </ACard>
  );
};

export default ExpandableCard;
